<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      .box {
        width: 100px;
        height: 2000px;
        background: linear-gradient(to bottom, red, pink);
      }
      #box2 {
        width: 200px;
        height: 50px;
        background: blueviolet;
        position: absolute;
        left: 200px;
        top: 100px;
      }
    </style>
  </head>
  <body>
    <div class="box"></div>
    <button>点击我滚回顶部</button>
    <div id="box2"></div>
    <script>
      var boxEle = document.getElementById("box2");
      var btn = document.querySelector("button");
      window.onscroll = function () {
        var num = document.body.scrollTop;
        if (num > 200) {
          boxEle.style.position = "fixed";
          boxEle.style.top = "0px";
        } else {
          boxEle.style.position = "absolute";
          boxEle.style.top = "100px";
        } //必须有else情况 判断当移动小于200的时候重新将 position: absolute;left: 200px;top: 50px,让盒子归回原位
      };
      btn.onclick = function () {
        var timer = setInterval(function () {
          document.body.scrollTop -= 10; //每隔5ms往上滑10
          var num = document.body.scrollTop;
          if (num <= 0) {
            clearInterval(timer); //点击回到顶点之后  可以往下滑
          }
        }, 5);
      };
    </script>
  </body>
</html>
